package com.yf.course.modules.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.base.api.exception.ServiceException;
import com.yf.course.modules.course.entity.CourseDepart;
import com.yf.course.modules.course.mapper.CourseDepartMapper;
import com.yf.course.modules.course.service.CourseDepartService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
* <p>
* 课程部门业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2021-09-22 10:03
*/
@Service
public class CourseDepartServiceImpl extends ServiceImpl<CourseDepartMapper, CourseDepart> implements CourseDepartService {

    @Override
    public void saveAll(String courseId, List<String> departs) {

        // 先删除
        QueryWrapper<CourseDepart> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CourseDepart::getCourseId, courseId);
        this.remove(wrapper);

        // 再增加
        if(CollectionUtils.isEmpty(departs)){
            throw new ServiceException("请至少选择选择一个部门！！");
        }
        List<CourseDepart> list = new ArrayList<>();

        for(String code: departs){
            CourseDepart depart = new CourseDepart();
            depart.setDeptCode(code);
            depart.setCourseId(courseId);
            list.add(depart);
        }

        this.saveBatch(list);
    }

    @Override
    public List<String> listByExam(String courseId) {
        // 先删除
        QueryWrapper<CourseDepart> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CourseDepart::getCourseId, courseId);
        List<CourseDepart> list = this.list(wrapper);
        List<String> ids = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            for(CourseDepart item: list){
                ids.add(item.getDeptCode());
            }
        }

        return ids;
    }

    @Override
    public List<String> listUserIdByCourse(String courseId, Integer scope) {
        return baseMapper.listUserIdByCourse(courseId, scope);
    }

    @Override
    public boolean inList(String courseId, String deptCode) {
        QueryWrapper<CourseDepart> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(CourseDepart::getCourseId, courseId)
                .eq(CourseDepart::getDeptCode, deptCode);
        return this.count(wrapper) > 0;
    }
}
